/**
  为了兼容老的应用，这里是早期换下来的程序
 */


/*
 window.document.getElementPosition=function(el){
 var _t=0;
 var _l=0;
 if (document.documentElement.getBoundingClientRect){
 var box = el.getBoundingClientRect();
 var oDoc = el.ownerDocument;
 //alert(navigator.appVersion);
 if(navigator.userAgent.indexOf("MSIE 6.0") >= 0)
 {
 _t = box.top  -2+ getScrollTop(oDoc);
 _l = box.left  -2+ getScrollLeft(oDoc);
 }else
 {
 _t = box.top  + getScrollTop(oDoc);
 _l = box.left  + getScrollLeft(oDoc);
 }
 }else{
 while (el.offsetParent) {
 _t += el.offsetTop;
 _l += el.offsetLeft;
 el = el.offsetParent;
 }
 }
 return {top:_t,left:_l};
 };
 function getScrollTop(doc){
 doc = doc || document;
 return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
 }
 function getScrollLeft(doc){
 doc = doc || document;
 return Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);
 }
 */

 //模板注入算法
String.prototype.injectUI = function (obj) {
    var str = this;
    var escapeVariable = "\\";
    var variableBegin = "{{";
    var variableEnd = "}}";
    if (!str) return "";
    var iend = str.getLength();
    var i = 0;
    var ivb = -1;
    var ys = 0;
    var yd = 0;
    var out = new StringBuffer();
    while (i < iend) {
        var c = str.charAt(i);
        var old = ' ';
        if (i > 0) {
            old = str.charAt(i - 1);
        }
        if (ivb == -1 && escapeVariable != old && str.startsWith(variableBegin, i)) {
            ys = 0;
            yd = 0;
            ivb = i + variableBegin.getLength();
        } else if (ivb != -1) {
            if (c == '\"' && yd % 2 == 0) ys++;
            if (c == '\'' && ys % 2 == 0) yd++;

            if (ys % 2 == 0 && yd % 2 == 0 && old != escapeVariable && variableEnd == str.substring(i, i + variableEnd.getLength())) {
                var varName = str.substring(ivb, i);
                var oo = eval("obj[" + varName+"]");// $(varName).get("value");
                if (!oo) oo = "";
                out.append(oo);
                ivb = -1;
            }
        }
        else {
            if (escapeVariable == c && str.startsWith(variableBegin, i + 1)) {

            } else out.append(c);
        }
        i++;
    }
    return out.toString();
};
//--------------------------相册  使用 JScrollPanel 滚动面板代替 
//new JPhotoAlbum({container:$('put-photo-here'),data:imgArray,width:600,height:0});
var JPhotoAlbum = new Class({
    Implements: [Events, Options],
    options: {
        //container: $('albumIMGDiv'), //div容器
        data:[], //数据数组,格式 {title:'text',img:'*.jpg'}
        target:'_self',
        mousePause:true,
        autoPlay:true,
        startStep:0, //位置
        knobCss:'blueKnob',
        width: 0,
        height:0,
        thumbWidth:120,
        thumbHeight:60,
        sleep:5000,
        showTitle:true,
        link:''
//        onChange: $empty() //参数 是索
    },

    initialize: function(options) {
        this.setOptions(options);
        var cimg = this;
        this.imgDiv = new Element('div', {'class':'albumImgs'});
        this.aImg = new Element('a', {target:this.options.target});

        this.titleDiv = new Element('div', {'class':'albumImgTitle',html:'loading...'});
        this.titleDiv.setStyle('display', 'none');

        this.ImgPic = new Element('img', {'border':'0', 'src':this.options.data[0].img});
        this.stop = this.options.autoPlay;
        this.tempstat = this.options.autoPlay;


        //标题显示
        this.ImgPic.addEvent('mouseover', function() {
            cimg.titleDiv.setStyle('display', '');
            if (cimg.options.mousePause) {
                cimg.tempstat = cimg.timeClock?cimg.timeClock:false;
                cimg.pause();
            }
        });

        this.ImgPic.addEvent('mouseout', function() {
            cimg.titleDiv.setStyle('display', 'none');
            if (cimg.options.mousePause && cimg.tempstat)
                cimg.play();
        });

        //缩放大小
        this.ImgPic.addEvent('load', function() {
            var bl = 1;
            if (cimg.options.width > 0) {
                bl = cimg.options.width / this.width;
                this.width = this.width * bl;
                cimg.titleDiv.setStyle('width', this.width);
                if (cimg.options.height > 0)
                    this.height = this.height * bl;
            }
            else {
                this.width = cimg.options.width;
                cimg.titleDiv.width = this.width;
                this.height = cimg.options.height;
            }
        });

        if (this.options.showTitle)
            this.aImg.adopt(this.titleDiv, 'top');

        this.aImg.adopt(this.ImgPic);
        this.imgDiv.adopt(this.aImg);
        this.options.container.adopt(this.imgDiv);
        this.linksPane = new Element('div', {'class':'albumImgButtonPanel'});
        this.linksPane.setStyle('height', this.options.thumbHeight +14);

        var sliderPaneW = (this.options.thumbWidth + 4) * this.options.data.length;
        this.linksPane.setStyle('width', this.options.width);

        this.linksDiv = new Element('div', {'class':'albumImgButtons'});
        this.linksDiv.setStyle('width', sliderPaneW);

        this.options.data.each(function(da, index) {
            cimg.linksDiv.adopt(
                    new Element('img', {src:da.img,title:da.title,
                        styles:
                        {
                            width:cimg.options.thumbWidth,
                            height:cimg.options.thumbHeight
                        }
                        ,
                        events:
                        {
                            click:function() {
                                cimg.slider.set(index);
                            }
                        }
                    }));
        });

        this.linksPane.adopt(this.linksDiv);
        this.options.container.adopt(this.linksPane, 'bottom');

        //滚动条begin
        var sliderDiv = new Element('div', {'class':'dotSlider'});
        sliderDiv.setStyle('width', this.options.width);
        var knob = new Element('div', {'class':this.options.knobCss});
        sliderDiv.adopt(knob);
        this.linksPane.adopt(sliderDiv, 'bottom');
        //滚动条end

        var sliderW = this.linksPane.getStyle('width').toInt();
        this.fullw = cimg.ImgPic.getParent('div').getStyle('width').toInt() - 2;
        this.titleDiv.setStyle('width', this.fullw);
        this.slider = new Slider(sliderDiv, knob, {
            sliderSteps:sliderPaneW,
            range:[0,cimg.options.data.length],
            steps: 1,
            wheel: true,
            onComplete: function(step) {
                cimg.set(step);
            }
            ,
            onTick: function(pos) {
                cimg.linksPane.scrollLeft = pos * (sliderPaneW / sliderW);
                sliderDiv.setStyle('left', cimg.linksPane.scrollLeft);
                this.knob.setStyle('left', pos);

                var step = (sliderPaneW / cimg.fullw) * pos;
                step = (step / 100).toInt();
                if (step < 0) step = 0;
                if (step > cimg.options.data.length) step = cimg.options.data.length;
            }

        }).set(this.options.startStep);

        //定时函数
        if (!this.timeClock)
            this.timeClock = this.timer.periodical(this.options.sleep, this);

    },
    timer:function () {
        this.slider.step = this.slider.step + 1;
        if (this.slider.step>=this.options.data.length) this.slider.step = 0;
        this.slider.set(this.slider.step);
        this.fireEvent('change', this.options.data[this.slider.step]);
    }
    ,
    play:function() {
        if (!this.timeClock)
            this.timeClock = this.timer.periodical(this.options.sleep, this);
    },
    pause:function() {
        if (this.timeClock)
            $clear(this.timeClock);
        this.timeClock = false;
    }
    ,
    next:function() {
        this.slider.step = this.slider.step + 1;
        if (this.slider.step>=this.options.data.length) this.slider.step = 0;
        this.slider.set(this.slider.step);
    }
    ,
    previous:function() {
        this.slider.step = this.slider.step - 1;
        if (this.slider.step < 0) this.slider.step = this.options.data.length - 1;
        this.slider.set(this.slider.step);
    }
    ,
    set:function(step) {
        var photo=this;
        this.ImgPic.fade('0.1');
        (function (){
            var aArray = photo.linksDiv.getElements('img');
            aArray.removeClass('active');
            if (aArray[step])aArray[step].addClass('active');
            if (photo.options.data[step]) {
                photo.titleDiv.set('html', photo.options.data[step].title);
                if (photo.options.link && photo.options.link != '')
                    photo.aImg.set('href', photo.options.link);
                else
                if (photo.options.data[step].link)
                    photo.aImg.set('href', photo.options.data[step].link);
                else photo.aImg.set('href', 'javascript:void(0);');
                photo.ImgPic.set('src', photo.options.data[step].img);
            }
            photo.ImgPic.fade('1');
        }).delay(400);
    }
});



//-------------------------js模板表格，使用JDataTable 替代
var JsTable = new Class({
    Implements: Options,
    options: {
        parent:'', //主容器
        row:'', //一行模板
        url: false,
        format:false,
        turnPage:"turnPage"
		/*
        onLoadAfter:$empty()
		*/
    }
	,
    initialize: function(options) {
        this.setOptions(options);
        var rowObj = false;
        if (typeOf(this.options.row) == 'string')
            rowObj = $(this.options.row);
        else rowObj = this.options.row;
        var tmpDiv = new Element('div');
        tmpDiv.adopt(rowObj);
        this.options.template = tmpDiv.get('html');
        if (Browser.firefox)   //firefox 请求会被转换
            this.options.template = this.options.template.replace(/%7B/g, "{").replace(/%7D/g, "}");
        if (typeOf(this.options.parent) == 'string')
            this.options.parent = $(this.options.parent);
        if (typeOf(this.options.turnPage) == 'string')
            this.options.turnPage = $(this.options.turnPage);
        this.loadURL();
    }
    ,
    loadURL: function(url) {
        if (!url) url = this.options.url;
        //接收url方式和数组方式
        new Request.JSON({
            url: url,
            method:'GET', //必须
            encoding:'UTF-8',
            result : "JSON",
            link:'chain',
            tableObject:this,
            onFailure:this.showError,
            onSuccess:this.setData
        }).get();
    },
    showError: function(error) {
        var dialog = new JDialog.Alert({'message':error});
        dialog.show();
    }
    ,
    setData: function(data, append) {
        if (!append) this.clearAll();
        var myTb = this;
        if (this.options.tableObject) {
            myTb = this.options.tableObject;
            myTb.clearAll();
        }
        if (!data) return;
        if (data.list) {
            var format = myTb.options.format;
            var html = '';
            data.list.each(function(line) {
                if (format)
                    for (var key in format) {
                        if (eval('line.' + key) != undefined) {
                            eval('line.' + key + '=line.' + key + format[key]);
                        }
                    }
                html = html + myTb.options.template.substitute(line);
            });
            myTb.options.parent.set('html', html);
            html = false;
            if (data.turnPage && myTb.options.turnPage) {
                myTb.options.turnPage.set('html', data.turnPage);
                var turnButtons = myTb.options.turnPage.getElements('a');
                turnButtons.each(function(button) {
                    var ahref = button.get('href');
                    button.removeProperty("href");
                    button.addEvent('click', function() {
                        if ((Browser.ie6 || Browser.ie7) && (ahref.startsWith("http") && myTb.options.url != '')) {
                            var x = ahref.indexOf('?');
                            if (x != -1)ahref = ahref.substring(x, ahref.length);
                        }
                        if (myTb.options.url.indexOf('?') != -1 && ahref.indexOf('?') == 0)
                            ahref = ahref.replace('?', '&');
                        myTb.loadURL(myTb.options.url + ahref);
                    });
                });
            }
            if (myTb.options.onLoadAfter) myTb.options.onLoadAfter();
        }
    }
    ,
    appendRow:function(line) {
        var html = this.options.parent.get('html') + this.options.template.substitute(line);
        this.options.parent.set('html', html);
    }
    ,
    clearAll:function() {
        this.options.parent.set('html', '');
    }
});


//--------------------------图片滚动显示
var JChangeIMG = new Class({
    Implements: [Events, Options],
    options: {
        container: $('changeIMGDiv'), //div容器
        data:[], //数据数组,格式 {title:'text',img:'*.jpg',link:'*.html'}
        target:'_blank',
        width: 0,
        height:0,
        sleep:1500,
        showTitle:true,
        onChange: $empty() //参数 是索引
    },
    initialize: function(options) {
        this.setOptions(options);
        if (this.options.width < 1) this.options.width = this.options.container.getStyle('width').toInt();
        if (this.options.height < 1) this.options.height = this.options.container.getStyle('height').toInt();
        var cimg = this;
        this.imgDiv = new Element('div', {'class':'changeImgs'});
		if (!this.options.data||this.options.data.length<=0) return;
        this.aImg = new Element('a', {'target':this.options.target,'href':this.options.data[0].link});
        this.aImg.setStyle('width', this.options.width);
		if (this.options.height>0) this.aImg.setStyle('height', this.options.height);

        this.titleDiv = new Element('div', {'class':'changeImgTitle','html':this.options.data[0].title});
        this.titleDiv.setStyle('width', this.options.width);
        this.ImgPic = new Element('img', {'border':'0', 'src':this.options.data[0].img,
            'events':
            {
                'mouseover':function() {
                    cimg.stop = true;
                }
                ,
                'mouseout':function() {
                    cimg.stop = false;
                }
            }
        });
        this.ImgPic.setStyle('width', this.options.width);
        this.ImgPic.setStyle('height', this.options.height);

        if (this.options.showTitle) this.aImg.adopt(this.titleDiv);
        this.aImg.adopt(this.ImgPic);
        this.imgDiv.adopt(this.aImg);
        this.options.container.adopt(this.imgDiv);
        this.linksDiv = new Element('div', {'class':'changeImgButtons'});
        this.linksDiv.setStyle('width', this.options.width);

        this.options.data.each(function(da, index) {
            cimg.linksDiv.adopt(new Element('a', {'href':da.link, 'html':index + 1,
                'events':
                {
                    'mouseover':function() {
                        cimg.times = index;
                        cimg.changeImg();
                        cimg.stop = true;
                    }
                    ,
                    'mouseout':function() {
                        cimg.stop = false;
                    }
                }
            }));
        });
        this.options.container.adopt(this.linksDiv, 'bottom');
        this.times = 0;
        cimg.stop = false;
        this.isFade = false;
        this.changeImg.periodical(this.options.sleep, this);
    },
    //定时部分
    changeImg: function() {
        if (this.stop) return;
        if (!this.isFade) {
			this.ImgPic.set('opacity',0.1);
            this.ImgPic.fade('out');
            this.isFade = true;
        }
        var aArray = this.linksDiv.getElements('a');
        if (this.times >= aArray.length) this.times = 0;
		var t=this.times;
        aArray.each(function(e,i){
			if (e.hasClass('active')) e.removeClass('active');
			if (i==t) 
			{
				e.addClass('active');
				e.set('html',i+1);//兼容IE
			}
		});
        this.titleDiv.set('html', this.options.data[t].title);
        this.aImg.set('href', this.options.data[t].link);
        this.ImgPic.set('src', this.options.data[t].img);
        this.fireEvent('change', this.options.data[t]);
        this.fadeEnd.delay(100, this);
        this.times++;
    }
    ,
    fadeEnd:function() {
        this.ImgPic.fade('in');
        this.isFade = false;
    }
});
/**tagbox****/
var TagboxList = new Class({
    Implements: [Options, Events],
    plugins: [],
    options: {/*
     onFocus: $empty,
     onBlur: $empty,
     onBitFocus: $empty,
     onBitBlur: $empty,
     onBitAdd: $empty,
     onBitRemove: $empty,
     onBitBoxFocus: $empty,
     onBitBoxBlur: $empty,
     onBitBoxAdd: $empty,
     onBitBoxRemove: $empty,
     onBitEditableFocus: $empty,
     onBitEditableBlue: $empty,
     onBitEditableAdd: $empty,
     onBitEditableRemove: $empty,*/
        prefix: 'tagboxList',
        split:' ',
        max: null,
        unique: true,
        uniqueInsensitive: true,
        endEditableBit: true,
        startEditableBit: true,
        hideEditableBits: true,
        inBetweenEditableBits: false,
        keys: {previous:DOMEvent.defineKeys.left, next: DOMEvent.defineKeys.right},
        bitsOptions: {editable: {}, box: {}},
        plugins: {},
        check: function(s) {
            return s.clean().replace(/this.options.split/g, '') != '';
        },
        encode: function(o) {
            return o.map(
                    function(v) {
                        v = v[0] ? v[0] : v[1];
                        return v ? v : null;
                    }).clean().join(this.options.split);
        },
        decode: function(o) {
            return o.split(this.options.split);
        }
    },
    initialize: function(element, options) {
        this.setOptions(options);
        this.container=$(element);
        if (this.container==null) return;
        this.original =this.container.setStyle('display', 'none').set('autocomplete', 'off').addEvent('focus', this.focusLast.bind(this));
        this.container = new Element('div', {'class': this.options.prefix}).inject(element, 'after');

        this.container.addEvent('click', function(e) {
            if ((e.target == this.list || e.target == this.container) &&
                    (!this.focused || $(this.current) != this.list.getLast())) this.focusLast();
        }.bind(this));
        this.list = new Element('ul', {'class': this.options.prefix + '-bits'}).inject(this.container);
        for (var name in this.options.plugins) this.enablePlugin(name, this.options.plugins[name]);
        ['check', 'encode', 'decode'].each(function(i) {
            this.options[i] = this.options[i].bind(this);
        }, this);
        this.afterInit();
    },

    enablePlugin: function(name, options) {
        this.plugins[name] = new TagboxList[name.camelCase().capitalize()](this, options);
    },

    afterInit: function() {
        if (this.options.unique) this.index = [];
        if (this.options.endEditableBit) this.create('editable', null, {tabIndex: this.original.tabIndex}).inject(this.list);
        var update = this.update.bind(this);
        this.addEvent('bitAdd', update, true).addEvent('bitRemove', update, true);
        document.addEvents({
            click: function(e) {
                if (!this.focused) return;
                if (e.target.className.contains(this.options.prefix)) {
                    if (e.target == this.container) return;
                    var parent = e.target.getParent('.' + this.options.prefix);
                    if (parent == this.container) return;
                }
                this.blur();
            }.bind(this),
            keydown: function(ev) {
                if (!this.focused || !this.current) return;
                var caret = this.current.is('editable') ? this.current.getCaret() : null;
                var value = this.current.getValue()[1];
                var special = ['shift', 'alt', 'meta', 'ctrl'].some(function(e) {
                    return ev[e];
                });
                var custom = special || (this.current.is('editable') && this.current.isSelected());
                switch (ev.code) {
                    case 8:
                        if (this.current.is('box')) {
                            ev.stop();
                            return this.current.remove();
                        }
                        break;
                    case this.options.keys.up:
                        if (this.current.is('box') || ((caret == 0 || !value.length) && !custom)) {
                            ev.stop();
                            this.focusRelative('previous');
                        }
                        break;
                    case 46:
                        if (this.current.is('box')) {
                            ev.stop();
                            return this.current.remove();
                        }
                        break;
                    case this.options.keys.pagedown:
                        if (this.current.is('box') || (caret == value.length && !custom)) {
                            ev.stop();
                            this.focusRelative('next');
                        }
                        break;
                }
            }.bind(this)
        });
        this.setValues(this.options.decode(this.original.get('value')));
    },

    create: function(klass, value, options) {
        if (klass == 'box') {
            if ((!value[0] && !value[1]) || value[1] && !this.options.check(value[1])) return false;
            if (this.options.max && this.list.getChildren('.' + this.options.prefix + '-bit-box').length + 1 > this.options.max) return false;
            if (this.options.unique && this.index.contains(this.uniqueValue(value))) return false;
        }
        return new TagboxListBit[klass.capitalize()](value, this, Object.merge(this.options.bitsOptions[klass], options));
    },

    uniqueValue: function(value) {
        return value[0] ? value[0] : (this.options.uniqueInsensitive ? value[1].toLowerCase() : value[1]);
    },

    onFocus: function(bit) {
        if (this.current) this.current.blur();
        $clear(this.blurtimer);
        this.current = bit;
        this.container.addClass(this.options.prefix + '-focus');
        if (!this.focused) {
            this.focused = true;
            this.fireEvent('focus', bit);
        }
    },

    onBlur: function(bit, all) {
        this.current = null;
        this.container.removeClass(this.options.prefix + '-focus');
        this.blurtimer = this.blur.delay(all ? 0 : 200, this);
    },

    onAdd: function(bit) {
        if (this.options.unique && bit.is('box')) this.index.push(this.uniqueValue(bit.value));
        if (bit.is('box')) {
            var prior = this.getBit($(bit).getPrevious());
            if ((prior && prior.is('box') && this.options.inBetweenEditableBits) || (!prior && this.options.startEditableBit)) 
			{
                var b = this.create('editable').inject(prior || this.list, prior ? 'after' : 'top');
                if (this.options.hideEditableBits) b.hide();
            }
        }
    },
    onRemove: function(bit) {
        if (!this.focused) return;
        if (this.options.unique && bit.is('box')) this.index.erase(this.uniqueValue(bit.value));
        var prior = this.getBit($(bit).getPrevious());
        if (prior && prior.is('editable')) prior.remove();
        this.focusRelative('next', bit);
    },

    focusRelative: function(dir, to) {
        var b = this.getBit($(to?to:this.current)['get' + dir.capitalize()]());
        if (b) b.focus();
        return this;
    },

    focusLast: function() {
        var lastElement = this.list.getLast();
        if (lastElement) this.getBit(lastElement).focus();
        return this;
    },

    blur: function() {
        if (! this.focused) return this;
        if (this.current) this.current.blur();
        this.focused = false;
        return this.fireEvent('blur');
    },

    add: function(plain, id, html, afterEl) {
        var b = this.create('box', [id, plain, html]);
        if (b) {
            if (!afterEl) afterEl = this.list.getLast('.' + this.options.prefix + '-bit-box');
            b.inject(afterEl || this.list, afterEl ? 'after' : 'top');
        }
        return this;
    },

    getBit: function(obj) {
        return (typeOf(obj) == 'element') ? obj.retrieve('tagboxList:bit') : obj;
    },

    getValues: function() {
        return this.list.getChildren().map(
                function(el) {
                    var bit = this.getBit(el);
                    if (bit.is('editable')) return null;
                    return bit.getValue();
                }, this).clean();
    },

    setValues: function(values) {
        if (!values) return;
        values.each(function(v) {
            if (v) this.add.apply(this, typeOf(v) == 'array' ? [v[1], v[0], v[2]] : [v]);
        }, this);
    },

    update: function() {
        this.original.set('value', this.options.encode(this.getValues()));
    }

});

var TagboxListBit = new Class({
    Implements: Options,
    initialize: function(value, tagboxList, options) {
        this.name = this.type.capitalize();
        this.value = value;
        this.tagboxList = tagboxList;
        this.setOptions(options);
        this.prefix = this.tagboxList.options.prefix + '-bit';
        this.typeprefix = this.prefix + '-' + this.type;
        this.bit = new Element('li').addClass(this.prefix).addClass(this.typeprefix).store('tagboxList:bit', this);
        this.bit.addEvents({
            mouseenter: function() {
                this.bit.addClass(this.prefix + '-hover').addClass(this.typeprefix + '-hover');
            }.bind(this),
            mouseleave: function() {
                this.bit.removeClass(this.prefix + '-hover').removeClass(this.typeprefix + '-hover');
            }.bind(this)
        });
    },

    inject: function(element, where) {
        this.bit.inject(element, where);
        this.tagboxList.onAdd(this);
        return this.fireBitEvent('add');
    },

    focus: function() {
        if (this.focused) return this;
        this.show();
        this.focused = true;
        this.tagboxList.onFocus(this);
        this.bit.addClass(this.prefix + '-focus').addClass(this.prefix + '-' + this.type + '-focus');
        return this.fireBitEvent('focus');
    },

    blur: function() {
        if (!this.focused) return this;
        this.focused = false;
        this.tagboxList.onBlur(this);
        this.bit.removeClass(this.prefix + '-focus').removeClass(this.prefix + '-' + this.type + '-focus');
        return this.fireBitEvent('blur');
    },

    remove: function() {
        this.blur();
        this.tagboxList.onRemove(this);
        this.bit.destroy();
        return this.fireBitEvent('remove');
    },

    show: function() {
        this.bit.setStyle('display', 'block');
        return this;
    },

    hide: function() {
        this.bit.setStyle('display', 'none');
        return this;
    },

    fireBitEvent: function(type) {
        type = type.capitalize();
        this.tagboxList.fireEvent('bit' + type, this).fireEvent('bit' + this.name + type, this);
        return this;
    },

    is: function(t) {
        return this.type == t;
    },

    setValue: function(v) {
        this.value = v;
        return this;
    },

    getValue: function() {
        return this.value;
    },

    toElement: function() {
        return this.bit;
    }
});

TagboxListBit.Editable = new Class({
    Extends: TagboxListBit,
    options: {tabIndex: null,growing: true,growingOptions: {},stopEnter: true,addOnBlur: false,addKeys: 13},
    type: 'editable',
    initialize: function(value, tagboxList, options) {
        this.parent(value, tagboxList, options);
        this.element = new Element('input', {type: 'text', 'class': this.typeprefix + '-input', autocomplete: 'off', value: this.value ? this.value[1] : ''}).inject(this.bit);
        if (this.options.tabIndex>0) this.element.tabIndex = this.options.tabIndex;
        if (this.options.growing) new GrowingInput(this.element, this.options.growingOptions);
        this.element.addEvents({
            focus: function() {
                this.focus(true);
            }.bind(this),
            blur: function() {
                this.blur(true);
                if (this.options.addOnBlur) this.toBox();
            }.bind(this)
        });
        if (this.options.addKeys || this.options.stopEnter) {
            this.element.addEvent('keydown', function(ev) {
                if (!this.focused) return;
                if (this.options.stopEnter && ev.code == DOMEvent.defineKeys.enter) ev.stop();
                if (Array.from(this.options.addKeys).contains(ev.code)) {
                    ev.stop();
                    this.toBox();
                }
            }.bind(this));
        }
    },

    focus: function(noReal) {
        this.parent();
        if (!noReal) this.element.focus();
        return this;
    },

    blur: function(noReal) {
        this.parent();
        if (!noReal) this.element.blur();
        return this;
    },

    getCaret: function() {
        if (this.element.createTextRange) {
            var r = document.selection.createRange().duplicate();
            r.moveEnd('character', this.element.value.length);
            if (r.text == '') return this.element.value.length;
            return this.element.value.lastIndexOf(r.text);
        } else return this.element.selectionStart;
    },

    getCaretEnd: function() {
        if (this.element.createTextRange) {
            var r = document.selection.createRange().duplicate();
            r.moveStart('character', -this.element.value.length);
            return r.text.length;
        } else return this.element.selectionEnd;
    },

    isSelected: function() {
        return this.focused && (this.getCaret() !== this.getCaretEnd());
    },
    setValue: function(val) {
        this.element.value = val[0] ? val[0] : val[1];
        if (this.options.growing) this.element.retrieve('growing').resize();
        return this;
    },
    getValue: function() {
        return [null, this.element.value, null];
    },
    toBox: function() {
        var value = this.getValue();
        var b = this.tagboxList.create('box', value);
        if (b){
            b.inject(this.bit, 'before');
            this.setValue([null, '', null]);
            return b;
        }
        return null;
    }
});

TagboxListBit.Box = new Class({
    Extends: TagboxListBit,
    options: {deleteButton: true},type: 'box',
    initialize: function(value, tagboxList, options) {
        this.parent(value, tagboxList, options);
        this.bit.set('html', this.value[2] ? this.value[2] : this.value[1]);
        this.bit.addEvent('click', this.focus.bind(this));
        if (this.options.deleteButton) {
            this.bit.addClass(this.typeprefix + '-deletable');
            this.close = new Element('a', {'class': this.typeprefix + '-deletebutton', events: {click: this.remove.bind(this)}}).inject(this.bit);
        }
		var child = this.bit.getChildren('??');
		if (child) child.addEvent('click', function(e) {
            e.stop();
        });
    }
});

(function() {
    GrowingInput = new Class({
        Implements: [Options, Events],
        options: {
            min: 0,
            max: null,
            startWidth: 2,
            correction: 15
        },
        initialize: function(element, options) {
            this.setOptions(options);
            this.element = $(element).store('growing', this).set('autocomplete', 'off');
            this.calc = new Element('span', {
                styles: {
                    float: 'left',
                    display: 'inline-block',
                    position: 'absolute',
                    left: -1000
                }
            }).inject(this.element, 'after');
            ['font-size', 'font-family', 'padding-left', 'padding-top', 'padding-bottom',
                'padding-right', 'border-left', 'border-right', 'border-top', 'border-bottom',
                'word-spacing', 'letter-spacing', 'text-indent', 'text-transform'].each(function(p) {
                this.calc.setStyle(p, this.element.getStyle(p));
            }, this);
            this.resize();

            var resize = this.resize.bind(this);
            this.element.addEvents({blur: resize, keyup: resize, keydown: resize, keypress: resize});
        },

        calculate: function(chars) {
            this.calc.set('html', chars);
            var width = this.calc.getStyle('width').toInt();
            return (width ? width : this.options.startWidth) + this.options.correction;
        },
        resize: function() {
            this.lastvalue = this.value;
            this.value = this.element.value;
            var value = this.value;
            if (this.options.min && this.value.length < this.options.min) {
                if (this.lastvalue && (this.lastvalue.length <= this.options.min)) return;
                value = str_pad(this.value, this.options.min, '-');
            } else if (this.options.max && this.value.length > this.options.max) {
                if (this.lastvalue && (this.lastvalue.length >= this.options.max)) return;
                value = this.value.substr(0, this.options.max);
            }
            this.element.setStyle('width', this.calculate(value));
            return this;
        }

    });

    var str_repeat = function(str, times) {
        return new Array(times + 1).join(str);
    };
    var str_pad = function(self, length, str, dir) {
        if (self.length >= length) return this;
        str = str || ' ';
        var pad = str_repeat(str, length - self.length).substr(0, length - self.length);
        if (!dir || dir == 'right') return self + pad;
        if (dir == 'left') return pad + self;
        return pad.substr(0, (pad.length / 2).floor()) + self + pad.substr(0, (pad.length / 2).ceil());
    };
})();











//---------------------窗体
var JspxFrom = new Class({
    Implements: [Options, Events],
    options: {
        container:'div.formContainer', //div容器
        readUrl:'/user/config/read.${suffix}',
        writeUrl:'/user/config/write.${suffix}',
        dialogWidth:200,
        dialogHeight:160
        /*
         onReadAfter: $empty(), //当前要发送请求的时候
       */
    }
    ,
    initialize:function (options) {
        this.setOptions(options);
        //this.fromTop = new Element('div',{html:'<b class="b1"></b><b class="b2"></b><b class="b3"></b><b class="b4"></b>'});
        //this.fromFooter = new Element('div',{html:'<b class="b5"></b><b class="b6"></b><b class="b7"></b><b class="b8"></b>'});

        var f = this;
        var formContainerArray = $$(this.options.container);
        this.canRead = (formContainerArray&&formContainerArray.length>0);
        if (this.canRead) formContainerArray.each(function(form){
            var title = form.get('caption');
            var parent=form.getParent();
            //parent.adopt(f.fromTop,'top');
            parent.adopt(form);
            //parent.adopt(f.fromFooter,'bottom');

            if (title)
            {
				var fromBtn = new Element('div',{'class':'pageConfig',html:'<a class="small" title="小字体"></a><a class="large" title="大字体"></a><a class="skin" title="换肤"></a><a class="mode" title="显示模式"></a><a class="help" title="帮助提示"></a>'});
				form.grab(fromBtn,'top');

				var titleCss = form.get('titleCss');
				if (!titleCss) titleCss = 'title';  //mTitPanel addconLogo
                var fromTitle = new Element('div',{'class':titleCss,html:'<span class="caption">' + title + '</span>'});
                form.grab(fromTitle,'top');

            }
		
            var helpTips = form.getElements('div.helpTip');
			if (helpTips) helpTips.each(function(helpDiv){
                var helpSlide = new Fx.Slide(helpDiv).hide();
                form.getElements('div.pageConfig a.help').addEvent('click', function(event){
                    event.stop();
                    helpSlide.toggle();
                });
            });
        });

        $$(this.options.container + ' div.pageConfig a.small ,' + this.options.container + ' div.pageConfig a.large').addEvent('click', function() {
            var fontSize = f.configData.fontSize.toInt();
            if (fontSize<=7) fontSize = 12;
            if (this.hasClass('small')) fontSize = fontSize - 2;
            else fontSize = fontSize + 2;
			if (fontSize<7) fontSize = 7;
            f.configData.fontSize = fontSize;

            f.saveConfig();
            f.refresh();
        });


        $$(this.options.container + ' div.title a.mode').addEvent('click', function() {

            var modeDlg = new Element('div',{'styles':{'width':300,'lineHeight':40,'height':40,'color':'#000'}});
            var accordionLabel = new Element('label',{'class':'radioLabel'});
            var accordionRadio = new Element('input',{'name':'viewMode',type:'radio','value':'accordion'});
            accordionLabel.adopt(accordionRadio);
            accordionLabel.appendText('手风琴');

            var tabLabel = new Element('label',{'class':'radioLabel'});
            var tabRadio = new Element('input',{'name':'viewMode',type:'radio','value':'tab'});
            tabLabel.adopt(tabRadio);
            tabLabel.appendText('标签切换');

            var indexingLabel = new Element('label',{'class':'radioLabel'});
            var indexingRadio = new Element('input',{'name':'viewMode',type:'radio','value':'indexing'});
            indexingLabel.adopt(indexingRadio);
            indexingLabel.appendText('索引平铺');

            if (f.configData.viewMode=='accordion')
            {
                accordionRadio.setProperty('checked','checked');
            }
            if (f.configData.viewMode=='tab')
            {
                tabRadio.setProperty('checked','checked');
            }
            if (f.configData.viewMode=='indexing')
            {
                indexingRadio.setProperty('checked','checked');
            }

            modeDlg.adopt(accordionLabel);
            modeDlg.adopt(tabLabel);
            modeDlg.adopt(indexingLabel);

            var dialog = new JDialog.Confirm({
                title: '用户偏好设置',
                width:240,
                message:modeDlg,
                callback:function(bool) {
                    if (bool)
                    {
                        var value = getRadioValue(modeDlg.getElements('input[name=viewMode]'));
                        if (!value) value = 'indexing';
                        f.configData.viewMode = value;
                        f.saveConfig();
                    }
                }
            });
            dialog.show();
        });

        $$(this.options.container + ' div.title a.skin').addEvent('click', function(e) {
            var point = window.document.mousePos(e.event);
            var skinDlg = new Element('div',{'align':'center','styles':{'width':500}});
            var skinBtn = new Element('div',{'id':'skin-buttons','class':'marqueeMenuPanel','styles':{'height':30}});
            var skinThumbnail = new Element('div',{'id':'skin-thumbnail','class':'marqueeScrollPanel','styles':{'height':60}});
            skinDlg.adopt(skinBtn);
            skinDlg.adopt(skinThumbnail);

            new Request({'url':'/share/background/skins.' + suffix, method: 'get', onSuccess: function(text){
                var skinUl = new Element('ul',{'html':text,'styles':{'display':'none'}});
                new JMarquee({container:skinThumbnail,button:skinBtn,transition:'elastic:out',showTitle:true,play:false,playMode:false,titleHeight:60,blockHeight:60,blockWidth:100,marginWidth:1,data:skinUl.getElements('li')});
            }}).send();

            var dialog = new JDialog.Alert({
                title: '皮肤选择框',
                top:point.y+20,
                left:(point.x-520),
                width:512,
                message:skinDlg
            });
            dialog.show();
        });

    }
    ,
    created:function()
    {
        return this.canRead;
    }
    ,
    readConfig:function()
    {
        var f = this;
        var myRequest = new Request.JSON({
            url:this.options.readUrl,
            method: 'post',
            onSuccess: function(data){
                if (data&&data.bundleList)
				{
                    configData = f.configData = data.bundleList;

                    if (isNaN(f.configData.fontSize))
                    {
                        f.configData.fontSize= 12;
                        f.configData.fontColor= '#000';
                        f.configData.borderColor= '#333';
                        f.configData.highlightColor= '#F93';
                        f.configData.highlightBackground= '#EBF8FC';
                    }
                    f.refresh();
                    f.fireEvent('readAfter',f.configData);
				}
            }
        });
        myRequest.send('r='  + Number.random(0,100));
    }
    ,
    refresh:function()
    {
        f = this;
       //f.configData 将配置数据设置到窗体
        

/*
		f = this;
        var aArray = this.fromTitle.getElements('a');
        if (aArray&&aArray.length>0)
        {
            aArray.addEvent('mouseenter', function() {
                this.setStyle('background-color',f.configData.highlightColor);
            });
            aArray.addEvent('mouseleave', function() {
                this.setStyle('background-color','');
            });
        }
		var b18 = $$('b.b1,b.b8');
		if (b18&&f.configData&&f.configData.borderColor)
			b18.setStyles('background-color',f.configData.borderColor);
	 
        var elArray = $$('b.b2,b.b3,b.b4,b.b5,b.b6,b.b7,div.formContainer');
	
		if (elArray&&this.configData&&this.configData.borderColor)
			elArray.setStyles('border-color',this.configData.borderColor);


        var formRows = $$('div.formContainer div.row');
        if (formRows&&formRows.length>0)
        {

            formRows.setStyle('border-color',this.configData.borderColor);
            formRows.setStyle('font-size',f.configData.fontSize-0);
            var inputArray = $$('input','textarea','select');
            if (inputArray&&inputArray.length>0) inputArray.setStyle('font-size',f.configData.fontSize-0);

            var noteArray = $$('div.formContainer span.note');
            if (noteArray&&noteArray.length>0)
            {
                noteArray.setStyle('color',f.configData.noteFontColor);
            }

            formRows.addEvent('mouseenter', function() {
                this.setStyle('background',f.configData.highlightBackground);
            });
            formRows.addEvent('mouseleave', function() {
                this.setStyle('background','none');
            });
        }


        window.document.body.setStyles({
            'background':this.configData.background,'color':this.configData.fontColor
        });

        if (this.configData &&(this.configData.background==undefined|| this.configData.background.indexOf('/1.jpg')!=-1))
        {
            var pageConfig = $$('div.formContainer div.pageConfig');
            pageConfig.setStyle('background-color','#4E80B9');
        }
*/
    }
    ,
    renderingSkin:function(el)
    {
/*
        if (el)
        {
            var imgEl = el.getElement('img');
            if (imgEl)
            {
                this.configData.background = imgEl.get('background');
                this.configData.borderColor = imgEl.get('borderColor');
                this.configData.fontColor = imgEl.get('fontColor');
                this.configData.fontSize = imgEl.get('fontSize').toInt();
                this.configData.highlightColor = imgEl.get('highlightColor');
                this.configData.noteFontColor = imgEl.get('noteFontColor');
                this.configData.highlightBackground = imgEl.get('highlightBackground');
                this.refresh();
                this.saveConfig();
            }
        }
*/
    }
    ,
    saveConfig:function()
    {
        var saveStr = "";
        for (var key in this.configData)
        {
            saveStr=saveStr + key+'='+this.configData[key] + '&';
        }
        if (saveStr.length>1) saveStr = saveStr.substring(0,saveStr.length-1);
        var f = this;
        var myRequest = new Request({
            url:f.options.writeUrl,
            method: 'POST',
            onSuccess: function(responseText){
                var dlg = new JDialog.Pop({
                    title: '消息提示',
                    height:f.options.dialogHeight,
                    width:f.options.dialogWidth,
                    message:responseText
                });
                dlg.show();
            }
        });
        myRequest.send(saveStr);
    }
});
